package com.tfsswx.jcyw.cpureaper;

import cn.hutool.system.oshi.OshiUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import oshi.util.FormatUtil;
import oshi.util.GlobalConfig;

import javax.annotation.PostConstruct;

/**
 * @author 张述江
 * @date 2023/8/17
 */
@Slf4j
@Component
public class CpuReaper {

    @Value("${mem:40}")
    private Integer mem;
    @Value("${cpu:30}")
    private Integer cpu;

    @PostConstruct
    public void cpuReaper() {
        GlobalConfig.set(GlobalConfig.OSHI_OS_WINDOWS_CPU_UTILITY, true);
        new Thread(() -> {
            while (true) {
                log.info("------------------------------");
                log.info("CPU已使用：{}%", ((int) (OshiUtil.getCpuInfo().getUsed() * 100 * 100 * 100 / OshiUtil.getCpuInfo().getToTal())) / 100.0);
                log.info("当前进程PID：{}", OshiUtil.getCurrentProcess().getProcessID());
                log.info("系统已使用内存：{}", FormatUtil.formatBytes(OshiUtil.getMemory().getTotal() - OshiUtil.getMemory().getAvailable()));
                log.info("进程已使用内存：{}", FormatUtil.formatBytes(OshiUtil.getCurrentProcess().getResidentSetSize()));
            }
        }).start();

        new Thread(new MemTask(mem)).start();
        int cpuCount = Runtime.getRuntime().availableProcessors() * cpu;
        for (int i = 0; i < cpuCount; i++) {
            new Thread(new CpuTask()).start();
        }
    }
}
